package com.bieyang.anjia.ui.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import com.bieyang.anjia.R;
import com.bieyang.anjia.module.FileModel;
import com.bieyang.anjia.module.LoginTypeEnum;
import com.bieyang.anjia.module.User;
import com.bieyang.anjia.sqlitedatabase.AnjiaSQLiteOpenHelper;
import com.bieyang.anjia.sqlitedatabase.SqliteOperation;
import com.bieyang.anjia.ui.adapter.AlarmAdapter;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SharedPrefsUtil;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.ShowProgress;
import com.bieyang.anjia.utils.SubUtils;

/**
 * 安信
 * 
 * @author M.y.q
 * 
 */
@SuppressLint("HandlerLeak")
public class AcAnXin extends BaseFlingActivity {
	String[] items;
	String memberId;
	boolean iSingle;
	String uuid;
	/**
	 * 每页个数
	 */
	int pageSize = 10;
	/**
	 * 底部加载更多
	 */
	View footView;
	SubUtils subUtils = new SubUtils();
	ArrayList<String> filePathArr = new ArrayList<String>();
	Context con;
	ListView AlarmHappenListView;
	AlarmAdapter alarmHappenAdapter;
	ArrayList<FileModel> alarmItemList;
	SqliteOperation sqlOperation;
	int alarmCode = -1;
	String table = "alarminfo";
	ShowProgress progressDialog;
	boolean sqlAllQueryed;
	MyServiceConnection conn;
	AnXinReceiver receiver = new AnXinReceiver();
	Handler uiHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				downLoadAndSaveinfo(msg);
				break;
			case 111:
				if (null != progressDialog) {
					progressDialog.dismiss();
				}
				Show.toast(con, R.string.down_load_failed);
				break;
			case 20:
				saveInfo(msg);
				break;
			case Constants.QUERY_ALARM_ALL_SUCCESS:
				if (null != progressDialog) {
					progressDialog.dismiss();
				}
				footView.setEnabled(true);
				int currentCount = alarmItemList.size();
				JSONArray dataAll = (JSONArray) msg.obj;
				if (null != dataAll && 0 != dataAll.length()) {
					for (int i = 0; i < dataAll.length(); i++) {
						JSONObject json;
						try {
							json = dataAll.getJSONObject(i);
							subUtils.saveDataToDataBase(con, sqlOperation, json);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
				int count = sqlQuery(alarmItemList.size() + "," + pageSize);
				if (count < 10) {
					sqlAllQueryed = true;
					AlarmHappenListView.removeFooterView(footView);
					footView.setVisibility(View.GONE);
				} else {
					footView.setVisibility(View.VISIBLE);
				}
				alarmHappenAdapter.notifyDataSetChanged();
				currentCount = alarmItemList.size();
				if (0 == currentCount) {
					AlarmHappenListView.removeFooterView(footView);
					Show.toast(con, R.string.no_data);
				}
				break;
			case Constants.QUERY_ALARM_ALL_FAILED:
				if (null != progressDialog) {
					progressDialog.dismiss();
				} else if (0 == alarmItemList.size()) {
					Show.toast(con, R.string.no_data);
				} else {
					Show.toast(con, R.string.internet_exception);
				}
				break;
			case Constants.GET_URL_SUCCESS:
				setCase(msg);
				break;
			case Constants.GET_URL_FAILED:
				if (null != progressDialog) {
					progressDialog.dismiss();
				}
				Show.toast(con, R.string.internet_exception);
				break;
			case 101:
				queryServer();
				break;
			default:
				break;
			}
		};
	};

	private class MyServiceConnection implements
			android.content.ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}

	}

	/**
	 * 更新本地文件路径
	 * 
	 * @param msg
	 */
	private void setCase(Message msg) {
		final FileModel model = (FileModel) msg.obj;
		if (model != null) {
			final String urlPath = model.urlPath;
			sqlOperation.update(table, "infoid=?", new String[] { model.infoId
					+ "" }, "urlpath", urlPath);
			sqlOperation.update(table, "infoid=?", new String[] { model.infoId
					+ "" }, "filetype", model.fileType);
			String strArr[] = urlPath.split(";");
			String fileType = model.fileType;
			Log.e("model.fileType", fileType + "");
			if (fileType.equals(".mp4")) {
				model.alarmMethod = "video";
			} else {
				if (strArr.length > 1) {
					model.alarmMethod = "three";
				} else {
					model.alarmMethod = "one";
				}
			}
			Log.e("alarmMethod", model.alarmMethod + "");
			sqlOperation.update(table, "infoid=?", new String[] { model.infoId
					+ "" }, "alarmmethod", model.alarmMethod);
			int currentCount = alarmItemList.size();
			alarmItemList.clear();
			sqlAllQueryed = false;
			sqlQuery("" + currentCount);
			alarmHappenAdapter.notifyDataSetChanged();
			if (null != urlPath && !"null".equals(urlPath)) {
				for (int i = 0; i < alarmItemList.size(); i++) {
					Log.e("nullPoint", i + "  position=" + model.position);
					Log.e("methods", alarmItemList.get(i).alarmMethod + "");
				}
				getLocalPath(model.position, urlPath);
			}
		} else {
			if (null != progressDialog) {
				progressDialog.dismiss();
			}
			Show.toast(con, R.string.internet_exception);
		}
	}

	/**
	 * 
	 * @param msg
	 */
	private void downLoadAndSaveinfo(Message msg) {
		FileModel model = (FileModel) msg.obj;
		if (model.alarmMethod.equals("three")) {
			if (filePathArr.size() != 3) {
				return;
			} else {
				model.filePath = filePathArr.get(0) + ";" + filePathArr.get(1)
						+ ";" + filePathArr.get(2);
			}
			alarmCode = 1;
		} else if (model.alarmMethod.equals("video")) {
			alarmCode = 0;
		} else if (model.alarmMethod.equals("one")) {
			alarmCode = 2;
		}
		sqlOperation.update("alarminfo", "urlpath=?",
				new String[] { model.urlPath }, "filepath", model.filePath);
		int currentCount = alarmItemList.size();
		alarmItemList.clear();
		sqlAllQueryed = false;
		refreshList(currentCount + "");
		alarmHappenAdapter.notifyDataSetChanged();
		if (null != progressDialog) {
			progressDialog.dismiss();
		}
		Intent intent = new Intent(con, AcAnxinAthome.class);
		intent.putExtra("alarmMethods", alarmCode);
		Bundle bubdle = new Bundle();
		bubdle.putSerializable("model", model);
		intent.putExtras(bubdle);
		startActivity(intent);
		filePathArr.clear();
		alarmCode = -1;
	}

	private void saveInfo(Message msg) {
		FileModel model = (FileModel) msg.obj;
		if (model.alarmMethod.equals("three")) {
			alarmCode = 1;
		} else if (model.alarmMethod.equals("video")) {
			alarmCode = 0;
		} else if (model.alarmMethod.equals("one")) {
			alarmCode = 2;
		}
		if (null != progressDialog) {
			progressDialog.dismiss();
		}
		Intent intent = new Intent(con, AcAnxinAthome.class);
		intent.putExtra("alarmMethods", alarmCode);
		Bundle bubdle = new Bundle();
		bubdle.putSerializable("model", model);
		intent.putExtras(bubdle);
		startActivity(intent);
		alarmCode = -1;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_tab_anxin);
		con = AcAnXin.this;
		items = new String[] { getString(R.string.delete_record) };
		iSingle = getIntent().getBooleanExtra("iSingle", false);
		uuid = getIntent().getStringExtra("uuid");
		memberId = SharedPrefsUtil.getStringValue(con, "memberId", "0");
		openDatabase();
		initView();
		initListener();
		initData();
	}

	private void initListener() {
		findViewById(R.id.btnBack).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		AlarmHappenListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				if (position == alarmItemList.size()) {
					return;
				}
				if (null == progressDialog) {
					progressDialog = SubUtils.showProgress(con);
				} else {
					progressDialog.show();
				}
				FileModel model = alarmItemList.get(position);
				if (null == model.urlPath || model.urlPath.equals("null")) {
					model.position = position;
					App.netManager.getAlarmUrl(model, uiHandler);
				} else {
					if (null == model.filePath || !fileIsExist(model.filePath)) {
						getLocalPath(position, model.urlPath);
					} else {
						Message msg = Message.obtain();
						msg.what = 20;
						msg.obj = model;
						uiHandler.sendMessage(msg);
					}
				}
			}
		});
		footView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!sqlAllQueryed) {
					footView.setEnabled(false);
					int count = sqlQuery(alarmItemList.size() + "," + pageSize);
					if (count < 10) {
						sqlAllQueryed = true;
						AlarmHappenListView.removeFooterView(footView);
						footView.setVisibility(View.GONE);
					} else {
						footView.setVisibility(View.VISIBLE);
					}
					alarmHappenAdapter.notifyDataSetChanged();
					footView.setEnabled(true);
				}
			}
		});
		AlarmHappenListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							final View view, final int position, long id) {
						final FileModel model = alarmItemList.get(position);
						new AlertDialog.Builder(con,
								AlertDialog.THEME_HOLO_LIGHT)
								.setTitle(model.name)
								.setItems(items,
										new DialogInterface.OnClickListener() {

											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												switch (which) {
												case 0:
													try {
														sqlOperation
																.update("alarminfo",
																		"infoid=?",
																		new String[] { model.infoId
																				+ "" },
																		"isdelete",
																		"T");
														if (null != model.filePath) {
															File file = new File(
																	model.filePath);
															file.delete();
														}
														subUtils.startDeleteAnimation(
																view, position,
																alarmItemList,
																alarmHappenAdapter);
													} catch (Exception e) {

													}
													break;

												default:
													break;
												}
											}
										}).show();

						return true;
					}
				});
	}

	private void initData() {
		if (null == progressDialog) {
			progressDialog = SubUtils.showProgress(con);
		} else {
			progressDialog.show();
		}
		if (App.isLogin) {
			queryServer();
		} else {
			login(con);
		}
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.ANXIN_NOTIFY);
		registerReceiver(receiver, filter);
	}

	@Override
	protected void onResume() {
		int limit = alarmItemList.size();
		alarmItemList.clear();
		sqlQuery(limit + "");
		alarmHappenAdapter.notifyDataSetChanged();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(receiver);
		if (conn != null) {
			unbindService(conn);
		}
		super.onDestroy();
	}

	/**
	 * 链接数据库
	 */
	void openDatabase() {
		if (null == sqlOperation) {
			sqlOperation = new SqliteOperation(con,
					AnjiaSQLiteOpenHelper.dbName, AnjiaSQLiteOpenHelper.version);
		}
	}

	void initView() {
		if (iSingle) {
			TextView titleName = (TextView) findViewById(R.id.titleName);
			titleName.setText(getString(R.string.anxin_recorder));
		}
		AlarmHappenListView = (ListView) findViewById(R.id.alarmHappenList);
		alarmItemList = new ArrayList<FileModel>();
		alarmHappenAdapter = new AlarmAdapter(alarmItemList, con);
		footView = getLayoutInflater().inflate(R.layout.pull_refresh, null);
		footView.setVisibility(View.GONE);
		// 添加底部容器
		AlarmHappenListView.addFooterView(footView);
		AlarmHappenListView.setAdapter(alarmHappenAdapter);
	}

	/**
	 * 生成本地文件路径
	 * 
	 * @param position
	 *            位置
	 * @param urlPath
	 *            下载路径
	 */
	private void getLocalPath(final int position, final String urlPath) {
		final FileModel model = alarmItemList.get(position);

		if (model.alarmMethod.toString().equals("three")) {
			final String url[] = urlPath.split(";");

			new Thread(new Runnable() {

				@Override
				public void run() {
					Looper.prepare();
					downLoad(url[0], model, position);
					Looper.loop();
				}
			}).start();
			new Thread(new Runnable() {

				@Override
				public void run() {
					Looper.prepare();
					downLoad(url[1], model, position);
					Looper.loop();
				}
			}).start();
			new Thread(new Runnable() {

				@Override
				public void run() {
					Looper.prepare();
					downLoad(url[2], model, position);
					Looper.loop();
				}
			}).start();
		} else {
			new Thread(new Runnable() {

				@Override
				public void run() {
					Looper.prepare();
					downLoad(urlPath, model, position);
					Looper.loop();
				}
			}).start();
		}

	}

	/**
	 * 文件是否存在
	 * 
	 * @param path
	 *            本地路径
	 * @return
	 */
	boolean fileIsExist(String path) {
		String pathArr[] = path.split(";");
		for (int i = 0; i < pathArr.length; i++) {
			File file = new File(pathArr[i]);
			if (!file.exists()) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 查询数据库
	 * 
	 * @param limit
	 *            限制几条
	 */
	int sqlQuery(String limit) {
		ArrayList<FileModel> queryList;
		if (iSingle) {
			queryList = sqlOperation.query(table,
					"uuid=? and memberid=? and isdelete = ?", new String[] {
							uuid, memberId, "F" }, limit);
		} else {
			queryList = sqlOperation.query(table,
					"memberid = ? and isdelete = ? ", new String[] { memberId,
							"F" }, limit);
		}
		alarmItemList.addAll(queryList);
		return queryList.size();
	}

	/**
	 * 刷新界面
	 * 
	 * @param limit
	 */
	void refreshList(String limit) {
		sqlQuery(limit);
		uiHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				alarmHappenAdapter.notifyDataSetChanged();
			}
		}, 1000);

	}

	/**
	 * 文件下载
	 * 
	 * @param url
	 *            路径
	 * @param map
	 * @param position
	 *            list偏移量
	 */
	private void downLoad(String url, FileModel model, int position) {
		HttpClient httpClient = new DefaultHttpClient();
		// GET
		HttpGet myGet = new HttpGet(url);
		try {
			HttpResponse response = httpClient.execute(myGet);
			String fileName = getFileName(response);
			if (null == fileName) {
				Show.toast(con, R.string.down_load_failed);
				return;
			}

			String filepath = null;
			if (".mp4".equals(model.fileType)) {
				filepath = subUtils.getFileFloderPath(con) + fileName
						+ Constants.VIDEO_SUFFIX;
			} else {
				filepath = subUtils.getFileFloderPath(con) + fileName
						+ Constants.PICTURE_SUFFIX;
			}
			File file = new File(filepath);
			file.getParentFile().mkdirs();
			model.filePath = filepath;
			FileOutputStream fileout = new FileOutputStream(file);
			InputStream is = response.getEntity().getContent();
			byte[] buffer = new byte[1024];
			int ch = 0;
			while ((ch = is.read(buffer)) != -1) {
				fileout.write(buffer, 0, ch);
			}
			is.close();
			fileout.flush();
			fileout.close();
			if (model.alarmMethod.toString().equals("three")) {
				filePathArr.add(filepath);
			}
			Message msg = Message.obtain();
			msg.what = 0;
			msg.obj = model;
			uiHandler.sendMessage(msg);
		} catch (Exception e) {
			filePathArr.clear();
			uiHandler.sendEmptyMessage(111);
			return;
		}
	}

	/**
	 * 获取response header中Content-Disposition中的filename值
	 * 
	 * @param response
	 * @return
	 */
	public static String getFileName(HttpResponse response) {
		Header contentHeader = response.getFirstHeader("Content-Disposition");
		String filename = null;
		if (contentHeader != null) {
			HeaderElement[] values = contentHeader.getElements();
			if (values.length == 1) {
				NameValuePair param = values[0].getParameterByName("filename");
				if (param != null) {
					try {
						filename = param.getValue();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
		return filename;
	}

	/**
	 * 安信接收器,用于实时刷新报警信息
	 * 
	 * @author M.y.q
	 * 
	 */
	public class AnXinReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(Constants.ANXIN_NOTIFY)) {
				uiHandler.sendEmptyMessage(101);
			}
		}
	}

	/**
	 * 登录
	 * 
	 * @param con
	 */
	private void login(Context con) {
		App.mContext = getApplicationContext();
		String phone = SharedPrefsUtil.getStringValue(con, "phone", null);
		String password = SharedPrefsUtil.getStringValue(con, "password", null);
		String uuid = SubUtils.getUuid(con);
		if (null != phone && null != password) {
			User user = new User();
			user.setCardNo(phone);
			user.setPassword(password);
			user.setUuid(uuid);
			user.setType(LoginTypeEnum.MAIN);
			SharedPrefsUtil.putValue(App.mContext, "loginType", "M");
			App.netManager.login(con, user, uiHandler);
		}
	}

	/**
	 * 访问服务器查询
	 */
	private void queryServer() {
		// if (iSingle) {
		// App.netManager.queryAlarm(con, uuid, uiHandler, sqlOperation
		// .queryColumn(table, "alarmtime", "uuid=? and memberid=?",
		// new String[] { uuid, memberId }));
		// } else {
		// }
		App.netManager.queryAlarmAll(con, uiHandler, sqlOperation.queryColumn(
				table, "alarmtime", "memberid=? ", new String[] { memberId }));
	}
}
